package com.echoesnet.echoesshortvideo.ViewModels;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import android.os.Environment;
import android.util.Log;

import com.echoesnet.echoesshortvideo.Api.Subscriber.SilenceSubscriber;
import com.echoesnet.echoesshortvideo.AppController;
import com.echoesnet.echoesshortvideo.Repositories.SettingRepository;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.FileUtils;
import com.echoesnet.echoesshortvideo.Utils.SharePreUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Copyright (C) 2018 科技发展有限公司
 * 完全享有此软件的著作权，违者必究
 *
 * @author ben
 * @version 1.0
 * @modifier
 * @createDate 2018/4/25 20:42
 * @description
 */
public class SettingViewModel extends ViewModel
{
    private static final String TAG = SettingViewModel.class.getSimpleName();

    public MutableLiveData<String> getLogout()
    {
        return logout;
    }

    private SettingRepository settingRepository;

    private MutableLiveData<String> logout = new MutableLiveData<>();
    private MutableLiveData<String> feedBackDetail = new MutableLiveData<>();
    private MutableLiveData<Map<String, String>> getSettingBack = new MutableLiveData<>();

    public MutableLiveData<Long> getClearBack()
    {
        return clearBack;
    }

    private MutableLiveData<Long> clearBack = new MutableLiveData<>();

    private MutableLiveData<String> getNoticeStateBack = new MutableLiveData<>();

    private MutableLiveData<String> getVersionInfoBack = new MutableLiveData<>();

    public LiveData<String> getFeedBack()
    {
        return feedBackDetail;
    }

    public LiveData<String> getVersionInfoBack()
    {
        return getVersionInfoBack;
    }

    public LiveData<Map<String, String>> getSettingBack()
    {
        return getSettingBack;
    }

    public LiveData<String> getNoticeStateBack()
    {
        return getNoticeStateBack;
    }


    public SettingViewModel()
    {
        this.settingRepository = new SettingRepository();
    }

    public void logout()
    {
        settingRepository.logout(new SilenceSubscriber<String>()
        {
            @Override
            public void onNext(String response)
            {
                super.onNext(response);
                //不需要删除的share字段添加到aLst中
                ArrayList<String> aLst = new ArrayList<String>();
                aLst.add("versionCode");
                SharePreUtils.removeValueExcludeSome(AppController.getInstance(), aLst);
                logout.setValue("ok");
            }
        });
    }

    public void postFeedBack(String deviceId, String content)
    {
        settingRepository.postFeedBack(deviceId, content, new SilenceSubscriber<String>()
        {
            @Override
            public void onNext(String response)
            {
                super.onNext(response);

                feedBackDetail.setValue(response);

            }
        });
    }

    public void getSettingState()
    {
        settingRepository.getSettingState(new SilenceSubscriber<String>()
        {
            @Override
            public void onNext(String response)
            {
                super.onNext(response);
                try
                {
                    JSONObject jsonObject = new JSONObject(response);
                    Map<String, String> map = new HashMap<>();
                    map.put("mobile", jsonObject.getString("mobile"));
                    map.put("notice", jsonObject.getString("notice"));
                    getSettingBack.setValue(map);
                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    public void changeNoticeState(String state)
    {
        settingRepository.changeNoticeState(state, new SilenceSubscriber<String>()
        {
            @Override
            public void onNext(String response)
            {
                super.onNext(response);
                getNoticeStateBack.setValue(state);

            }
        });
    }

    //版本信息
    public void getVersionUpdate(String versionCode, String deviceId)
    {
        settingRepository.getVersionUpdate(versionCode, deviceId, new SilenceSubscriber<String>()
        {
            @Override
            public void onNext(String response)
            {

                super.onNext(response);

                getVersionInfoBack.setValue(response);

            }
        });
    }


    //获得APP内部缓存
    private void getDirectory(File file)
    {
        //上级目录文件名字
        String outFileName = file.getName();

        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++)
        {
            if (files[i].isDirectory())
            {
                getDirectory(files[i]);
            }
            else
            {
                //删除CutVideo目录下所有文件
                if (outFileName.equals("CutVideo"))
                {
                    Log.d(TAG, "检测到要删除的缓存文件 文件名是：" + files[i].getName() + "文件大小是:" + files[i]
                            .length());
                    clearFileList.offerFirst(files[i]);
                    fileLength += files[i].length();
                }

                //删除camera目录下所有文件
                if (outFileName.equals("camera"))
                {
                    Log.d(TAG, "检测到要删除的缓存文件 文件名是：" + files[i].getName() + "文件大小是:" + files[i]
                            .length());
                    clearFileList.offerFirst(files[i]);
                    fileLength += files[i].length();
                }

            }
        }

    }



    //开始清除clearFileList里面文件
    public void clearFile()
    {
        File file = clearFileList.pollLast();
        if (file != null && file.exists())
        {
            if (file.isDirectory())
                FileUtils.deleteFile(file.getPath());
            else
                file.delete();
            clearFile();
        }

    }
    private long fileLength = 0;
    //要清除缓存的file队列
    private LinkedList<File> clearFileList;
    //检测缓存大小，并且把缓存文件标记 以备清除
    public void getCatchFileLength()
    {
        if (clearFileList == null)
            clearFileList = new LinkedList<>();

        fileLength = 0;
        clearFileList.clear();

        String path = CommonUtils.getRootDirPath(null);
        final File file = new File(path);

        //遍历所有file下的文件
        Observable.create(new ObservableOnSubscribe<String>()
        {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception
            {
                getDirectory(file);
                e.onNext("");
            }
        }).subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>()
                {
                    @Override
                    public void accept(String s) throws Exception
                    {

                        clearBack.setValue(fileLength);
                    }
                });

    }

}
